<template>
  <el-card class="box-card" style="width: 1450px">
    <!-- --------------------  搜索------------------------------- -->
    <div slot="header" class="clearfix">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input
            v-model="query.staffRealName"
            placeholder="用户名"
            :clearable="true"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="query.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始注册日期"
            end-placeholder="结束注册日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-row>
            <el-col :span="20">
              <el-button type="primary" @click="loadUsers"
                ><i class="el-icon-search"></i
              ></el-button>
              <el-button type="success" @click="dialog.addshow = true"
                >添加</el-button
              >
              <el-button type="success" @click="exportExcel"
                >导出数据</el-button
              >
            </el-col>
            <el-col :span="4">
              <el-upload
                class="clearfix"
                action="http://localhost:9000/users/importExcel"
                name="file"
                :on-progress="onExcelProgress"
                :on-success="handleExcelSuccess"
                accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                multiple
                :limit="1"
                :headers="upload.headerObj"
              >
                <el-button type="primary">数据导入</el-button>
              </el-upload>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
    <!-- ----------------------表格--------------------------- -->
    <el-table
      :data="staffList"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
      border
      style="width: 100%"
    >
      <el-table-column prop="staffId" label="编号" width="120">
      </el-table-column>
      <el-table-column prop="staffRealName" label="姓名" width="120">
      </el-table-column>
      <el-table-column prop="staffEmail" label="邮箱" width="180">
      </el-table-column>
      <el-table-column prop="staffDate" label="入职日期" width="120">
      </el-table-column>
      <el-table-column prop="staffBirthday" label="员工生日" width="120">
      </el-table-column>
      <el-table-column prop="staffPhone" label="电话号码" width="180">
      </el-table-column>
      <el-table-column label="头像" show-overflow-tooltip width="160">
        <template slot-scope="scope">
          <el-link @click="downLoad(scope.row.staffBy1)" target="_blank">
            <img
              :src="scope.row.staffBy1"
              alt=""
              style="width: 60px; height: 60px"
            />
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="deptName" label="部门" width="120">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row.staffId)"
            >编辑</el-button
          >
          <el-popconfirm
            title="这是一段内容确定删除吗？"
            @confirm="handleDelete(scope.row.staffId)"
          >
            <el-button slot="reference" size="mini" type="danger"
              >删除</el-button
            >
          </el-popconfirm>
          <el-button
            type="danger"
            size="mini"
            @click="assignRole(scope.row.staffId)"
            >分配角色</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.currentPage"
      :page-sizes="page.pageSizes"
      :page-size="query.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total"
    >
    </el-pagination>
    <!-- -----------------------添加dialog------------------------------------------------------ -->
    <el-dialog title="添加用户" :visible.sync="dialog.addshow" width="30%">
      <el-form :model="addForm" :rules="rules" ref="addForm">
        <el-row>
          <el-col :span="12"
            ><el-form-item
              label="姓名"
              :label-width="formLabelWidth"
              prop="empName"
            >
              <el-input v-model="addForm.empName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="性别" :label-width="formLabelWidth">
              <el-input v-model="addForm.empSex" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="年龄" :label-width="formLabelWidth">
              <el-input v-model="addForm.empAge" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="住址" :label-width="formLabelWidth">
              <el-input v-model="addForm.empAdd" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="头像" prop="empHeadImg" hidden>
              <el-input v-model="addForm.empHeadImg" clearable></el-input>
            </el-form-item>
            <el-form-item label="账号" :label-width="formLabelWidth">
              <el-input v-model="addForm.empAcc" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth">
              <el-input
                v-model="addForm.empPassword"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="生日" :label-width="formLabelWidth">
              <el-date-picker
                v-model="addForm.empBirthday"
                type="date"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item label="部门" :label-width="formLabelWidth">
              <el-select v-model="addForm.deptId" placeholder="请选择部门">
                <el-option
                  v-for="(dept, index) in deptList"
                  :key="index"
                  :label="dept.deptName"
                  :value="dept.deptId"
                ></el-option>
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:8888/uploadoss"
              name="file"
              :headers="upload.headerObj"
              :show-file-list="false"
              :on-success="handleSuccess"
              :before-upload="beforeUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.addshow = false">取 消</el-button>
        <el-button type="primary" @click="addUser">提 交</el-button>
      </div>
    </el-dialog>

    <!-- -----------------------修改dialog------------------------------------------------------ -->
    <el-dialog title="修改用户" :visible.sync="dialog.updateshow" width="30%">
      <el-form :model="form">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="updateForm.empName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-input v-model="updateForm.empSex" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" :label-width="formLabelWidth">
          <el-input v-model="updateForm.empAge" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址" :label-width="formLabelWidth">
          <el-input v-model="updateForm.empAdd" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="账号" :label-width="formLabelWidth">
          <el-input v-model="updateForm.empAcc" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input
            v-model="updateForm.empPassword"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="生日" :label-width="formLabelWidth">
          <el-date-picker
            v-model="updateForm.empBirthday"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="部门" :label-width="formLabelWidth">
          <el-select v-model="updateForm.deptId" placeholder="请选择部门">
            <el-option
              v-for="(dept, index) in deptList"
              :key="index"
              :label="dept.deptName"
              :value="dept.deptId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.updateshow = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">提 交</el-button>
      </div>
    </el-dialog>

    <!-- -----------------------授角色dialog------------------------------------------------------ -->
    <el-dialog
      title="用户授权"
      :visible.sync="dialog.assingRolesVisible"
      width="30%"
    >
      <el-checkbox-group v-model="checkList">
        <el-checkbox
          :label="item.roleId"
          v-for="(item, index) in roleList"
          :key="index"
          >{{ item.roleName }}</el-checkbox
        >
      </el-checkbox-group>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.assingRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRole">提 交</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: "",
      upload: {
        headerObj: {
          //Spring security时需要传递token，否则不需要该配置
          Authorization: sessionStorage.getItem("authorization"),
        },
      },
      uid: 0,
      checkList: [], //选中的角色
      roleList: [], //所有角色
      staffList: [],
      deptList: [],
      page: {
        pageSizes: [5, 10, 20, 50, 100], //下拉列表中的数组
        total: 0, //一共有多少条数据
      },
      query: {
        currentPage: 1, //代表当前页
        pageSize: 5, //代表每页显示多少条数据
        empName: "",
        dateRange: [],
      },
      dialog: {
        addshow: false,
        updateshow: false,
        assingRolesVisible: false,
      },
      addForm: {},
      updateForm: {},
      rules: {
        tel: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        region: [
          { required: true, message: "请选择活动区域", trigger: "change" },
        ],
        date1: [
          {
            type: "date",
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
        date2: [
          {
            type: "date",
            required: true,
            message: "请选择时间",
            trigger: "change",
          },
        ],
        type: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个活动性质",
            trigger: "change",
          },
        ],
        resource: [
          { required: true, message: "请选择活动资源", trigger: "change" },
        ],
        desc: [{ required: true, message: "请填写活动形式", trigger: "blur" }],
      },
    };
  },
  methods: {
    handleExcelSuccess(res, result) {
      this.$message.success("导入成功");
      if (result.response.success) {
        this.loadUsers();
      }
    },
    // 上传中
    onExcelProgress() {},
    exportExcel() {
      this.$axios
        .post("users/exportExcel", this.query, { responseType: "blob" })
        .then((res) => {
          let fileName = res.headers["content-disposition"].split("=")[1]; //得到后端生成的文件名
          let url = window.URL.createObjectURL(new Blob([res.data]));
          let dom = document.createElement("a");
          dom.style.display = "none";
          dom.href = url;
          dom.setAttribute("download", fileName); //指定下载后的文件名，防跳转
          document.body.appendChild(dom);
          dom.click();
          // 释放内存
          dom.parentNode.removeChild(dom);
          window.URL.revokeObjectURL(dom.href);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    // 下载文件
    downLoad(picture) {
      let pic = picture.substr(picture.lastIndexOf("/") + 1);
      this.$axios
        .get("/downLoadFile", {
          params: { filename: pic },
          responseType: "blob",
        })
        .then((res) => {
          let url = window.URL.createObjectURL(new Blob([res.data]));
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", pic); //指定下载后的文件名，防跳转
          document.body.appendChild(link);
          link.click();
          // 释放内存
          window.URL.revokeObjectURL(link.href);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    handleSuccess(res, file) {
      //this.imageUrl = URL.createObjectURL(file.raw);
      this.imageUrl = res.message; //显示
      this.addForm.headImg = res.message; //表单提交时传给服务器的
    },
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    updateRole() {
      this.$axios
        .post("roles", {
          empId: this.uid,
          roleIds: this.checkList,
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.$message.success("授权成功");
            this.dialog.assingRolesVisible = false;
            this.checkList = [];
            this.uid = 0;
          }
        });
    },
    assignRole(id) {
      this.dialog.assingRolesVisible = true;
      this.$axios.get("/roles/" + id).then((res) => {
        this.uid = id;
        this.roleList = res.data.data.roleList;
        this.checkList = res.data.data.checkList;
      });
    },
    loadUsers() {
      this.$axios.post("/staffs/query", this.query).then((res) => {
        this.staffList = res.data.data.staffList;
        this.page.total = res.data.data.total;
      });
    },
    loadDepts() {
      this.$axios.get("/depts").then((res) => {
        this.deptList = res.data.data.deptList;
      });
    },
    addUser() {
      this.$axios.post("/emps", this.addForm).then((res) => {
        if (res.data.code == 200) {
          this.dialog.addshow = false; //关掉模态框
          this.loadUsers(); //重新加载数据
          this.$refs.addForm.resetFields();
          //this.addForm = {}
        }
      });
    },
    updateUser() {
      this.$axios.put("/emps", this.updateForm).then((res) => {
        if (res.data.code == 200) {
          this.dialog.updateshow = false; //关掉模态框
          this.loadUsers(); //重新加载数据
        }
      });
    },
    handleEdit(empId) {
      //显示修改模态框
      this.dialog.updateshow = true;
      //查询对应的数据
      this.$axios.get("/emps/" + empId).then((res) => {
        this.updateForm = res.data.data.emp;
      });
    },
    handleDelete(empId) {
      //查询对应的数据
      this.$axios.delete("/emps/delete/" + empId).then((res) => {
        if (res.data.code == 200) {
          this.$message.success("删除成功");
          this.loadUsers(); //重新加载数据
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    handleSizeChange(val) {
      //当每页数据改变时
      this.query.pageSize = val;
      this.loadUsers();
    },
    handleCurrentChange(val) {
      //当点击页码时
      this.query.currentPage = val;
      this.loadUsers();
    },
  },
  mounted() {
    this.loadUsers();
    this.loadDepts();
  },
};
</script>
<style>
.clearfix{
  margin-right: 0px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>